package com.computer.fundamentals.networkprogram;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * TCP客户端负责发送连接请求并传输数据
 */
public class TCPClient {

    public static void main(String[] args) {
        OutputStream outputStream = null;
        InputStream inputStream = null;

        try {
            // 创建socket，指定连接的是本机的端口号为12345的服务器socket
            Socket socket = new Socket("127.0.0.1", 12345);
            // 获取输入输出流
            outputStream = socket.getOutputStream();
            inputStream = socket.getInputStream();
            // 将要传递给服务器的字符串转换为bytes数组，并将数组写入输出流
            outputStream.write(new String("我是客户端，请服务器兄弟赶紧回复！").getBytes());
            // 读取输入流并打印
            int len;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) != -1) {
                String str = new String(buffer, 0, len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}